package com.poobo.mqtest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {

    public static Channel channel = null;
    public static String host = "192.168.8.60";
    public static String username = "admin";
    public static String password = "admin";
    Thread subscribeThread;

    private synchronized static Channel getChannel() {

        if (channel == null || !channel.isOpen()) {
            //通道为空或未打开
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(host);
            factory.setUsername(username);
            factory.setPassword(password);
            Connection connection = null;
            try {
                connection = factory.newConnection();
                channel = connection.createChannel();
                return channel;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            return null;
        }
        return channel;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText editText = (EditText) findViewById(R.id.msg);
        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false); // user touches widget on phone with touch screen
        editText.setClickable(false);
        //用于从线程中获取数据，更新ui
        final Handler incomingMessageHandler = new Handler() {

            public void handleMessage(Message msg) {
                String message = msg.getData().getString("msg");
                EditText editText = (EditText) findViewById(R.id.msg);
                Date now = new Date();
                SimpleDateFormat ft = new SimpleDateFormat("HH:mm:ss");

                Editable editable = editText.getText();

                editable.insert(editable.length(), ft.format(now) + "收到：" + message + "\n\n");
//                Toast.makeText(MainActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
                Log.i("test", "msg:" + msg.toString());
            }
        };
        //开启消费者线程
        subscribe(incomingMessageHandler);


    }


    /**
     * 消费者线程
     */
    void subscribe(final Handler handler) {
        subscribeThread = new Thread(new Runnable() {
            @Override
            public void run() {


                    try {
                        channel = getChannel();

                        String alias = "hello";
                        try {
                            channel.queueDeclare(alias, false, false, false, null);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        channel.basicQos(1);
//                        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
                        Consumer consumer = new DefaultConsumer(channel) {

                            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                                    throws IOException {
                                String message = new String(body, "UTF-8");

                                //从message池中获取msg对象更高效
                                Message msg = handler.obtainMessage();
                                Bundle bundle = new Bundle();
                                bundle.putString("msg", message);
                                msg.setData(bundle);
                                handler.sendMessage(msg);

                            }
                        };
                        channel.basicConsume(alias, true, consumer);


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }



        });
        subscribeThread.start();
    }


    public void recdMsg() throws IOException {
        channel = getChannel();

        String alias = "hello";
        channel.queueDeclare(alias, false, false, false, null);
        channel.basicQos(1);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        Consumer consumer = new DefaultConsumer(channel) {

            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");

                TextView t = (TextView) findViewById(R.id.msg);
                t.setText(message);

            }
        };
        channel.basicConsume(alias, true, consumer);
    }
}
